package org.easydarwin.easyrtc;

import android.content.Context;
import android.content.DialogInterface;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.eju.cy.drawableview.DrawableView;
import com.eju.cy.drawableview.DrawableViewConfig;
import com.eju.cy.drawableview.draw.SerializablePath;
import com.eju.cy.drawableview.listener.GestureListener;

import org.easydarwin.conf.Config;
import org.easydarwin.easyrtc.databinding.ActivityMainBinding;
import org.easydarwin.util.AccountUtil;
import org.easydarwin.util.DensityUtils;
import org.easydarwin.util.LogUtil;
import org.easydarwin.util.PathFileUtil;
import org.easydarwin.util.PreferenceManager;
import org.easydarwin.util.SocketUtil;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

    ActivityMainBinding binding;
    PlayFragment play;
    PushFragment pusher;
    private DrawableViewConfig config = new DrawableViewConfig();
    private boolean mouseUp;

    private LinearLayout llPusher , llPlayer;
    private int screenWight , screenHeight;
    private int smallWight , smallHeight;
    private LinearLayout control;
//    private int controlWidth , controlHeight;
    private boolean isCustom;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        llPusher = (LinearLayout) findViewById(R.id.ll_pusher);
        llPlayer = (LinearLayout) findViewById(R.id.ll_player);

        initParam();
        isCustom =AccountUtil.isCustom("");
        String url = getIntent().getStringExtra("play_url");
        initDrawControl(isCustom);

        SocketUtil.getInstance().initSocket();
        SocketUtil.getInstance().setHandler(handler);

        LogUtil.i("=================要播放的视频地址=playUrl = " + url);
        if(!TextUtils.isEmpty(url)){
            String res =  url.substring(url.lastIndexOf("/") +1, url.lastIndexOf("."));
            String fromAccount = res.split("_")[0];
            PreferenceManager.getInstance().setFriendAccount(fromAccount);
            SocketUtil.getInstance().setFriendAccout(fromAccount);
        }
//        changePushPlaySize(isCustom);
    }

    private void initParam(){
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        screenHeight = dm.heightPixels;
        screenWight = dm.widthPixels;

//        screenWight = DensityUtils.dp2px(this , 100);
//        screenHeight = DensityUtils.dp2px(this , 200);

        smallWight = DensityUtils.dp2px(this , 100);
        smallHeight = DensityUtils.dp2px(this , 200);

        LogUtil.i("============MainActivity -- initParam----screenWight = " +screenWight +"-----screenHeight = " + screenHeight +"-------smallWight = " + smallWight +"---------smallHeight = " + smallHeight);
    }

    private void initDrawControl(boolean isCustom){
        control = (LinearLayout)findViewById(R.id.ll_control);
        initUI();
        binding.paintView.setCanDrawLine(!isCustom);
        control.setVisibility(isCustom ? View.GONE:View.VISIBLE);
    }

    /**
     * 切换 push play大小（）
     * @param prominentPush 凸显push
     */
    private void changePushPlaySize(boolean prominentPush){
        LogUtil.i("=======================mainActivity-----changePushPlaySize----prominentPush = " + prominentPush);
        RelativeLayout.LayoutParams playerParams = (RelativeLayout.LayoutParams)llPusher.getLayoutParams();
        RelativeLayout.LayoutParams pusherParams = (RelativeLayout.LayoutParams)llPusher.getLayoutParams();
        int marginTop = DensityUtils.dp2px(this, 20);
        int marginRight = DensityUtils.dp2px(this, 20);
        if(prominentPush){
            pusherParams.width = screenWight;
            pusherParams.height = screenHeight;
            llPusher.setLayoutParams(pusherParams);

            playerParams.width = smallWight;
            playerParams.height = smallHeight;
            playerParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            playerParams.setMargins(0 ,marginTop  , marginRight ,0);
            llPlayer.setLayoutParams(playerParams);
        }else{
            pusherParams.width = smallWight;
            pusherParams.height = smallHeight;
            pusherParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            pusherParams.setMargins(0 ,marginTop  , marginRight ,0);
            llPusher.setLayoutParams(pusherParams);

            playerParams.width = screenWight;
            playerParams.height = screenHeight;
            llPlayer.setLayoutParams(playerParams);
        }
    }

    public void onSettings(View view) {
//        Intent intent = new Intent(this, SettingActivity.class);
//        startActivity(intent);
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.pusher);
        LogUtil.i("==============fragment =" + fragment);
    }

    private void initUI() {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        config.setStrokeColor(getResources().getColor(android.R.color.holo_green_light));
        config.setShowCanvasBounds(true);
        config.setStrokeWidth(20.0f);
        config.setMinZoom(1.0f);
        config.setMaxZoom(3.0f);
        config.setCanvasHeight(dm.heightPixels);
        config.setCanvasWidth(dm.widthPixels);
        binding.paintView.setConfig(config);

        binding.strokeWidthPlusButton.setOnClickListener(new View.OnClickListener() {

            @Override public void onClick(View v) {
                config.setStrokeWidth(config.getStrokeWidth() + 10);
            }
        });
        binding.strokeWidthMinusButton.setOnClickListener(new View.OnClickListener() {

            @Override public void onClick(View v) {
                config.setStrokeWidth(config.getStrokeWidth() - 10);
            }
        });
        binding.changeColorButton.setOnClickListener(new View.OnClickListener() {

            @Override public void onClick(View v) {
                Random random = new Random();
                config.setStrokeColor(
                        Color.argb(255, random.nextInt(256), random.nextInt(256), random.nextInt(256)));
            }
        });
        binding.undoButton.setOnClickListener(new View.OnClickListener() {

            @Override public void onClick(View v) {
                binding.paintView.undo();
            }
        });


        binding.paintView.setTouchListener(new DrawableView.TouchListener() {
            @Override
            public void touch() {
                ArrayList<SerializablePath> paths = binding.paintView.getPaths();
                if(mouseUp){
                    int controlHeight = control.getHeight();
                    LogUtil.i("=========================controlHeight= " + controlHeight);
                    SocketUtil.getInstance().sendPath2Server(paths , controlHeight , screenWight + Config.sizeSplit + screenHeight);
                }
            }
        });

        binding.paintView.setGestureListener(new GestureListener() {
            @Override
            public void up() { mouseUp = true;  }
            @Override
            public void move() {  mouseUp = false;}
            @Override
            public void down() { mouseUp = false;}
        });
    }


    private Handler handler=new Handler(){
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    break;
                case Config.getRemotePath:
                    try {
                        reTryDrawRemotePath(msg);
                    } catch (JSONException e) {
                        LogUtil.e("==========parse Json exception");
                        LogUtil.e(e);
                        e.printStackTrace();
                    }
                    break;
            }
        };
    };

    private void reTryDrawRemotePath(android.os.Message msg) throws JSONException {
        String message = (String) msg.obj;
        LogUtil.i("=====================获取的数据 = message =  " + message);
        if(message.contains(Config.prefix)){
            String account = org.easydarwin.util.PreferenceManager.getInstance().getAccount();
            SocketUtil.getInstance().sendAcount2Server(account);

            LogUtil.i("=====================连接服务器成功,您的 " + message);
        }else{
            JSONObject object = new JSONObject(message);
            String strMsg = object.getString("msg");
            int transY = object.getInt("translateY");
            String size = object.getString("curScreenSize");
            int fromScreenW = Integer.parseInt(size.split(Config.sizeSplit)[0]);
            int fromScreenH = Integer.parseInt(size.split(Config.sizeSplit)[1]);
            float zoomX = (screenWight * 1.0f / fromScreenW );
            float zoomY = (screenHeight * 1.0f / fromScreenH );
            LogUtil.i("====================MainActiviy-----fromServer---transY = " + transY + "----FromScreenSize = " + size + "---screenWight = "+ screenWight +"--------screenHeight = " + screenHeight);
            ArrayList<SerializablePath> linePath = PathFileUtil.getInstance().getPathsFromJson(strMsg , transY , zoomX , zoomY);
            if(null == linePath || linePath.size() == 0){
                LogUtil.i("=====================获取的数据 is null ");
                return ;
            }
            LogUtil.i("=====================获取的数据 " + linePath.size() );
            binding.paintView.setPaths(linePath);
        }
    }

    @Override
    public void onBackPressed() {
        LogUtil.i("=======================MainActivity-------onBackPressed = " );
        final PushFragment pushFragment = (PushFragment)getSupportFragmentManager().findFragmentById(R.id.pusher);
        final PlayFragment playFragment = (PlayFragment)getSupportFragmentManager().findFragmentById(R.id.player);

        boolean isStreaming ;//mMediaStream != null && mMediaStream.isStreaming();
        if(isCustom){
            isStreaming = playFragment.isPushStreaming();
        }else{
            isStreaming = pushFragment.isPushStreaming();
        }
        LogUtil.i("=======================MainActivity-------isCustom = " + isCustom +"-------isStreaming = " + isStreaming);
        if (isStreaming ) {
            new AlertDialog.Builder(this).setTitle("是否允许后台上传？").setMessage("您设置了使能摄像头后台采集,是否继续在后台采集并上传视频？如果是，记得直播结束后,再回来这里关闭直播。").setNeutralButton("后台采集", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    MainActivity.super.onBackPressed();
                }
            }).setPositiveButton("退出程序", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                    LogUtil.i("=======================MainActivity-------isCustom = " + isCustom +"------- destoryResoure ");
                    pushFragment.destoryResoure();
                    playFragment.destoryResoure();
                    MainActivity.super.onBackPressed();
//                    Toast.makeText(MainActivity.this, "程序已退出。", Toast.LENGTH_SHORT).show();
                }
            }).setNegativeButton(android.R.string.cancel, null).show();
            return;
        } else {
            super.onBackPressed();
        }
    }
}
